package com.uls.hdh.service.impl;

import java.util.*;


import com.uls.common.core.domain.entity.SysUser;
import com.uls.hdh.vo.TaskCommentVo;
import com.uls.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;

import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.hdh.mapper.HdhPollsMapper;
import com.uls.hdh.domain.HdhPolls;
import com.uls.hdh.service.IHdhPollsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 投票事项Service业务层处理
 * 
 * @author hdh
 * @date 2024-11-08
 */
@Service
public class HdhPollsServiceImpl implements IHdhPollsService 
{
    @Autowired
    private HdhPollsMapper hdhPollsMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private ISysUserService userService;  //去用户名

    @Autowired
    private HistoryService historyService;

    /**
     * 查询投票事项
     * 
     * @param pollId 投票事项主键
     * @return 投票事项
     */
    @Override
    public HdhPolls selectHdhPollsByPollId(Long pollId)
    {
        return hdhPollsMapper.selectHdhPollsByPollId(pollId);
    }

    /**
     * 查询投票事项列表
     * 
     * @param hdhPolls 投票事项
     * @return 投票事项
     */
    @Override
    public List<HdhPolls> selectHdhPollsList(HdhPolls hdhPolls)
    {
        return hdhPollsMapper.selectHdhPollsList(hdhPolls);
    }

    /**
     * 新增投票事项
     * 
     * @param hdhPolls 投票事项
     * @return 结果
     */
    @Override
    public int insertHdhPolls(HdhPolls hdhPolls)
    {
        return hdhPollsMapper.insertHdhPolls(hdhPolls);
    }

    /**
     * 修改投票事项
     * 
     * @param hdhPolls 投票事项
     * @return 结果
     */
    @Override
    public int updateHdhPolls(HdhPolls hdhPolls)
    {
        return hdhPollsMapper.updateHdhPolls(hdhPolls);
    }

    /**
     * 批量删除投票事项
     * 
     * @param pollIds 需要删除的投票事项主键
     * @return 结果
     */
    @Override
    public int deleteHdhPollsByPollIds(Long[] pollIds)
    {
        return hdhPollsMapper.deleteHdhPollsByPollIds(pollIds);
    }

    /**
     * 删除投票事项信息
     * 
     * @param pollId 投票事项主键
     * @return 结果
     */
    @Override
    public int deleteHdhPollsByPollId(Long pollId)
    {
        return hdhPollsMapper.deleteHdhPollsByPollId(pollId);
    }




    /**
     * 启动流程
     * @param pollId
     * @param userId
     */
    @Override
    @Transactional
    public int submit(Long pollId, Long userId) {
        HdhPolls hdhPolls=hdhPollsMapper.selectHdhPollsByPollId(pollId);

        String processDefiKey ="myVoteProcess";
        Map<String, Object> variables = new HashMap<String,Object>();
        variables.put("inputUser1",userId);
        variables.put("inputUser2",121l);  //先写死，是主任的编号
        //没有启动这个流程
        if (hdhPolls.getStatus()==0) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            hdhPolls.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));  // 把流程实例id与业务系统绑定
            hdhPolls.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee(""+userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());

            return  hdhPollsMapper.updateHdhPolls(hdhPolls);
        }
        //流程启动了，打回重新审批，就不用再启动流程
        else{

            Long flowInstantId=hdhPolls.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());
            hdhPolls.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return  hdhPollsMapper.updateHdhPolls(hdhPolls);
        }
    }

    @Override
    @Transactional
    public List<HdhPolls> noFinishTask(Long userId, String processDefiniionKey) {
        List<HdhPolls> listHdhPolls=new ArrayList<HdhPolls>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("输入投票申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    //根据流程id查询mapper的方法
                    HdhPolls hdhPolls = hdhPollsMapper.selectHdhPollsFlowId(flowInstanceId);
                    listHdhPolls.add(hdhPolls);
                }

            }
        }

        return listHdhPolls;
    }
    @Override
    @Transactional
    public List<HdhPolls> noFinishTask(Long userId, String processDefiniionKey, HdhPolls hdhPolls) {
        List<HdhPolls> listHdhPolls=new ArrayList<HdhPolls>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("输入申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    hdhPolls.setFlowInstantId(flowInstanceId);
                    //根据流程id和其他条件查询mapper的方法
                    HdhPolls hdhPolls1 = hdhPollsMapper.selectHdhPollsFlowIdOther(hdhPolls);
                    if (hdhPolls1!=null)
                        listHdhPolls.add(hdhPolls1);
                }

            }
        }

        return listHdhPolls;
    }

    @Override
    @Transactional
    public void completeTask(Long flowInstantId, Integer agree, Long userId, String comment, Long pollId) {
        HdhPolls hdhPolls=hdhPollsMapper.selectHdhPollsByPollId(pollId);

        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstantId)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();

        if (list != null && list.size() > 0) {
            for (Task task : list) {

                if (task.getName().equals("主任审批")){
                    if (agree==1){
                        params.put("inputUser3", 122l);  //固定一个人员
                        hdhPolls.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    }else {
                        hdhPolls.setStatus(1l);
                    }
                    params.put("pass1", agree);  //给流程变量赋值

                }else if (task.getName().equals("院长审批")){
                    if (agree==1){
                        params.put("inputUser4", 123l);  //固定一个人员
                        hdhPolls.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    }else {
                        hdhPolls.setStatus(1l);
                    }
                    params.put("pass2", agree);  //给流程变量赋值
                }else if (task.getName().equals("校长审批")){
                    if (agree==1){
                        hdhPolls.setStatus(3l);
                    }
                    else {
                        hdhPolls.setStatus(1l);
                    }
                    params.put("pass3", agree);  //给流程变量赋值
                }

                hdhPollsMapper.updateHdhPolls(hdhPolls);

                // 添加批注时候的审核人，通常应该从session获取,现在从redis
                Authentication.setAuthenticatedUserId(userId.toString());
                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                // taskId：任务id
                taskService.complete(task.getId(), params);

            }
        }

    }

    //查询审批历史
    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {

        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments(""+flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo=new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            SysUser user=userService.selectUserById(Long.parseLong(com.getUserId()));  //查询用户名

            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist= historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if(hist!=null&&hist.size()>0){
                HistoricTaskInstance historicTaskInstance=hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }

            taskCommentVoList.add(taskCommentVo);

        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();

        for(int i= taskCommentVoList.size()-1;i>=0;i--)
        {
            TaskCommentVo temp=taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }

        return taskCommentVoListSort;
    }

    @Override
    public List<HdhPolls> finishTask(Long userId, String processDefiniionKey) {
        List<HdhPolls> listFinishPolls = new ArrayList<HdhPolls>();
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance temp : list) {
                if (!temp.getName().equals("输入申请")) {
                    Long flowInstanceId = Long.parseLong(temp.getProcessInstanceId());
                    HdhPolls hdhPolls = hdhPollsMapper.selectHdhPollsFlowId(flowInstanceId);
                    listFinishPolls.add(hdhPolls);
                }
            }
        }
        List<HdhPolls> listFinishPolls1 =new ArrayList<>(new HashSet<>(listFinishPolls));
        return listFinishPolls1;
    }


    @Override
    public List<HdhPolls> finishTask(Long userId, String processDefiniionKey,HdhPolls hdhPollsQuery) {
        List<HdhPolls> listFinishPolls = new ArrayList<HdhPolls>();
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance temp : list) {
                if (!temp.getName().equals("输入申请")) {
                    Long flowInstanceId = Long.parseLong(temp.getProcessInstanceId());
                    hdhPollsQuery.setFlowInstantId(flowInstanceId);
                    HdhPolls hdhPolls = hdhPollsMapper.selectHdhPollsFlowIdOther(hdhPollsQuery);
                    if(hdhPolls!=null)
                       listFinishPolls.add(hdhPolls);
                }
            }
        }
        List<HdhPolls> listFinishPolls1 =new ArrayList<>(new HashSet<>(listFinishPolls));
        return listFinishPolls1;
    }


}
